<?php

declare(strict_types=1);

namespace app\service\order;

use app\model\Order;
use think\facade\Db;

class AssistAssignService
{
    public function assign(?int $regionId = null): ?int
    {
        $candidates = $this->fetchCandidates();
        if ($candidates === []) {
            return null;
        }

        $bestUser = null;
        $bestLoad = PHP_INT_MAX;

        $activeStatuses = [
            Order::STATUS_PENDING_CONFIRM,
            Order::STATUS_PENDING_PAYMENT,
            Order::STATUS_PENDING_ASSIGN,
            Order::STATUS_PENDING_LOGISTICS,
        ];

        foreach ($candidates as $userId) {
            $load = Order::where('assist_user_id', $userId)
                ->whereIn('status', $activeStatuses)
                ->count();

            if ($load < $bestLoad) {
                $bestLoad = $load;
                $bestUser = $userId;
            }
        }

        return $bestUser;
    }

    private function fetchCandidates(): array
    {
        $rows = Db::name('auth_user_role')
            ->alias('aur')
            ->join('auth_role ar', 'ar.id = aur.role_id')
            ->where('ar.slug', 'support')
            ->where('aur.status', 1)
            ->whereNull('aur.delete_time')
            ->order('aur.update_time', 'asc')
            ->column('aur.user_id');

        $unique = array_values(array_unique(array_map('intval', $rows)));

        return $unique;
    }
}
